/**
 * 
 */
package net.loyintean.pearlshell.logcenter.jms.impl;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import net.loyintean.pearlshell.logcenter.jms.IJmsSender;
import net.loyintean.pearlshell.logcenter.model.ILogModel;

/**
 * @author Administrator
 * 
 */
public class JmsSenderImpl implements IJmsSender {

	/**
	 * JMS 客户端到JMS Provider 的连接
	 */
	private Connection connection = null;

	/**
	 * 消息的目的地;消息发送给谁.
	 */
	private Destination destination;

	/**
	 * 构造方法，创建，并完成初始化。
	 */
	public JmsSenderImpl() {
		super();
	}

	/**
	 * 
	 * @see net.loyintean.pearlshell.logcenter.jms.IJmsSender
	 *      #send(net.loyintean.pearlshell.logcenter.model.ILogModel)
	 */
	@Override
	public void send(ILogModel log) throws JMSException {
		assert log != null;
		assert connection != null;
		assert destination != null;

		Session session = connection.createSession(true,
				Session.AUTO_ACKNOWLEDGE);

		MessageProducer producer = session.createProducer(destination);
		producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		try {
			sendMessage(session, producer, log);

			session.commit();
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			if (null != session) {
				session.close();
			}
		}

	}

	public boolean init(ConnectionFactory factory, String destinationName) {
		boolean result = true;

		try {
			connection = factory.createConnection();

			connection.start();

			Session session = connection.createSession(true,
					Session.AUTO_ACKNOWLEDGE);

			destination = session.createQueue(destinationName);

		} catch (JMSException e) {
			e.printStackTrace();
			result = false;
		}

		return result;
	}

	private void sendMessage(Session session, MessageProducer producer,
			ILogModel log) throws JMSException {
		ObjectMessage message = session.createObjectMessage(log);
		producer.send(message);
	}

	/**
	 * @param connection
	 *            the connection to set
	 */
	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	/**
	 * @param destination
	 *            the destination to set
	 */
	public void setDestination(Destination destination) {
		this.destination = destination;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.loyintean.pearlshell.logcenter.jms.IJmsSender#close()
	 */
	@Override
	public void close() throws JMSException {
		if (connection != null) {
			connection.close();
		}

	}

}
